<?php

namespace app\admin\controller\user;

use app\admin\service\QrcodeService;
use app\common\controller\Backend;
use app\common\library\Auth;
use app\common\library\Token;
use fast\Random;
use think\Cookie;
use think\Queue;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname';
    public $payMode = [];

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\User;
    }

    /**
     * View
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
           /*if($sort == 'user.id'){
               $order = "asc";
           }*/

            $list = $this->model
                ->with('group')
                ->where('is_delete',-1)
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);
                $v->tui_nums = db('user')->where('parent_id', $v->id)->count();
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * Add
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $params['email'] = $params['username'];
            $msg = $this->validate($params,'User');
            if($msg != 'true')
                $this->error($msg);

            $params['createtime'] = $params['updatetime'] = $params['jointime'] = time();
            if(empty($params['nickname'])){
                $params['nickname'] = $params['nickname_en'];
            }
            unset($params['id']);
            if(empty($params['password'])){
                $this->error("请设置一个密码");
            }
            $findOne = db('user')->where('username',$params['username'])->find();
            if($findOne){
                $this->error(__('Username already exist'));
            }
            if(!empty($params['mobile'])){
                $findOne = db('user')->where('mobile',$params['mobile'])->find();
                if($findOne){
                    $this->error(__('Mobile already exist'));
                }
            }
            if(!empty($params['birthday'])){
                $now = new \DateTime();
                $birthDate = new \DateTime($params['birthday']);

                // 获取当前年份和月份
                $nowYear = $now->format('Y');
                $nowMonth = $now->format('m');

                // 获取出生年份和月份
                $birthYear = $birthDate->format('Y');
                $birthMonth = $birthDate->format('m');
                // 计算年份差
                $age = $nowYear - $birthYear;
                $params['age'] = $age;
            }
            $authLib = new Auth();
            $params['salt'] = Random::alnum();
            $params['password'] = $authLib->getEncryptPassword($params['password'], $params['salt']);
            $params['status'] = 'hidden';
            $params['joinip'] = $this->request->ip();
            $uid = db('user')->insertGetId($params);
            $bianhao = config('global.custom_bianhao')+$uid;
            db('user')->where('id',$uid)->update(['bianhao'=>$bianhao]);

            //創建完畢生成一个二维码
          /*  try {
                $qrcodeServiceHandle = new QrcodeService();
                $text = $qrcodeServiceHandle->getQrcodeText($uid);
                $qrcodePath = $qrcodeServiceHandle->makeQroce($text,$uid);
                $qrcodePath = str_replace(ROOT_PATH."public",'',$qrcodePath);
                db('user')->where('id',$uid)->update(['qrcode'=>$qrcodePath]);
            }catch (\Exception $e){

            }*/

            $this->success(__('Add Success'));
        }



        $this->view->assign('row',[]);
        $this->view->assign('gender',0);
        $this->view->assign('avatar','/assets/img/avatar.png');
        $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), 0, ['class' => 'form-control selectpicker']));
        return $this->view->fetch('edit');
    }

    /**
     * Edit
     */
    public function edit($ids = null)
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");


            $params['nickname'] = $params['username'];
//            unset($params['birthday']);
            $findOne = db('user')->where("id",'<>',$params['id'])->where('username',$params['username'])->find();
            if($findOne){
                $this->error(__('Username already exist'));
            }
            if(!empty($params['mobile'])){
                $findOne = db('user')->where("id",'<>',$params['id'])->where('mobile',$params['mobile'])->find();
                if($findOne){
                    $this->error(__('Mobile already exist'));
                }
            }

            //是否存在修改密碼
            if(!empty($params['password'])){
                $authLib = new Auth();
                $params['salt'] = Random::alnum();
                $params['password'] = $authLib->getEncryptPassword($params['password'], $params['salt']);
            }else{
                unset($params['password']);
            }
            if(!empty($params['birthday'])){
                $now = new \DateTime();
                $birthDate = new \DateTime($params['birthday']);

                // 获取当前年份和月份
                $nowYear = $now->format('Y');
                $nowMonth = $now->format('m');

                // 获取出生年份和月份
                $birthYear = $birthDate->format('Y');
                $birthMonth = $birthDate->format('m');
                // 计算年份差
                $age = $nowYear - $birthYear;
                $params['age'] = $age;
            }
            db('user')->update($params);
            $this->success(__('Operation Success'));
        }
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->view->assign('avatar',$row['avatar']);
        $this->view->assign('gender',$row['gender']);
        $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
        return parent::edit($ids);
    }

    /**
     * Del
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $idsArr = explode(',',$ids);
        foreach ($idsArr as $id){
            $row = $this->model->get($id);
            $this->modelValidate = true;
            if (!$row) {
                $this->error(__('No Results were found'));
            }
            //如果用户已有 订阅 已有购买 软删除

            $has_order = db('cloudphone_order')->where('user_id',$row['id'])->find();
            if(empty($has_order)){
                //真删除
                Auth::instance()->delete($row['id']);
            }else{
                //软删除
                db('user')->where('id',$row['id'])->update(['is_delete'=>1]);
                Token::clear($row['id']);
            }


        }
        $this->success(__('Operation Success'));
    }

    /**
     * Login
     */
    public function login($ids = null){
        if(empty($ids)){
            $this->error(__('Error Parame'));
        }
        $userInfo = db('user')->find($ids);
        $auth = Auth::instance();
        $account = $userInfo['username'];
        $auth->login($account, "lamp7918I");
        $expire = input('post.keeplogin') ? 30 * 86400 : 3600*24*2;
        Cookie::set('uid', $userInfo['id'], $expire);
        Cookie::set('token', $auth->getToken(), $expire);
        Cookie::set('oauth_login', $userInfo['id'], $expire);
        $go_url = request()->domain()."/index/user/index";
        $this->success('ok','',['go_url'=>$go_url]);
    }
}
